#pragma once

#include "vector2d.h"
#include "character.h"
#include "enemyai.h"
#include "map.h"
#include "drawable.h"

#include "lua/lua_main.h"	// for dofile, and Lua_State

class Game : public Updatable
{
protected:
	Drawable* list[3];
	
	/** the characters in the game */
	Character* chars[2];
	/** the map */
	Map m;
	int input;
	bool running;

	lua_State * L;
public:
	void m_load(const char * filename)
	{
		m.load(filename);
	}
	Game()
		:input(0),running(true)
	{
		chars[0] = new Character();
		chars[1] = new EnemyAI(1);
		// the second character is targeting the first
		chars[1]->Recieve(EnemyAI::MSG_TARGET, chars[0]);
		// map should be loaded by LUA
		//m.load("volcano.txt");
		// set up the characters
		chars[0]->set(Vector2D(4,5),1,Character::Colors::LtGreen);
		chars[1]->set(Vector2D(5, 5),2,Character::Colors::LtRed);
		// put the map and characters in the display list
		list[0] = &m;
		list[1] = chars[0];
		list[2] = chars[1];
	}
	void setLua(lua_State * l)
	{
		L = l;
	}
	Character * getChar(int a_index)
	{
		return chars[a_index];
	}
	char mapGet(int x, int y)
	{
		return m.get(x, y);
	}
	~Game()
	{
		printf("the destructor is being called!");
	}
	void draw()
	{
		// note: change if list becomes dynamic (vs static)
		int listSize = sizeof(list)/sizeof(Drawable*);
		for(int i = 0; i < listSize; ++i)
		{
			list[i]->draw();
		}
	}
	void handleInput(){input = _getch();running = input != 'q';}
	bool isRunning(){return running;}
	void setRunning(bool a_run){running = a_run;}
	void Update(float secondsPassed)
	{
		chars[0]->move(input);
		// clear the input after it is read once...
		input = 0;
		chars[1]->Update(secondsPassed);

		const int numberOfChars = sizeof(chars)/sizeof(Character*);
		//check for forgivness
		for(int i=0; i<numberOfChars; ++i){
			Vector2D charPos = chars[i]->getVector2D();
			if(charPos.x < 0
				|| charPos.x >= m.getWidth()
				|| charPos.y < 0
				|| charPos.y >= m.getHeight()
				|| m.get(charPos.x, charPos.y)=='#'){
					chars[i]->goBack();
			}
		}
		dofile(L, "update.lua");
	}
};